package helper;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class RSAHelper {
	/**
	 * 通过PKCS#8编码的Key指令获得私钥对象
	 * */
	public static RSAPrivateKey getPrivateKey(String privateKey) {
		KeyFactory keyFactory;
		try {
			keyFactory = KeyFactory.getInstance(util.Constants.RSA);
			byte[] buffer = Base64.getDecoder().decode(privateKey);
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(buffer);
			RSAPrivateKey key;
			try {
				key = (RSAPrivateKey)keyFactory.generatePrivate(pkcs8KeySpec);
				return key;
			} catch (InvalidKeySpecException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}
}
